<template>
  <div class="min-h-screen bg-gray-50">
    <div class="px-4 pt-4">
      <nav class="text-sm text-gray-500 flex items-center space-x-2">
        <NuxtLink to="/" class="text-blue-600 hover:underline">首页</NuxtLink>
        <span>/</span>
        <span class="text-gray-700">结算记录</span>
      </nav>
    </div>
    <!-- 页面标题 -->
    <div class="text-center py-6">
      <h1 class="text-xl font-medium text-gray-900">结算记录</h1>
    </div>

    <div class="p-4">
      <!-- 统计卡片 -->
      <div v-if="statistics" class="grid grid-cols-3 gap-4 mb-6">
        <div class="bg-white rounded-lg p-4 text-center">
          <div class="text-2xl font-bold text-blue-600">{{ statistics.total_count }}</div>
          <div class="text-sm text-gray-600">总记录数</div>
        </div>
        <div class="bg-white rounded-lg p-4 text-center">
          <div class="text-2xl font-bold text-green-600">￥{{ statistics.total_commission }}</div>
          <div class="text-sm text-gray-600">总收入</div>
        </div>
        <div class="bg-white rounded-lg p-4 text-center">
          <div class="text-2xl font-bold text-orange-600">{{ statistics.pending_count }}</div>
          <div class="text-sm text-gray-600">处理中</div>
        </div>
      </div>

      <!-- 筛选器 -->
      <div class="bg-white rounded-lg p-4 mb-4">
        <div class="flex space-x-4">
          <select
            v-model="filters.status"
            @change="fetchSettlements"
            class="flex-1 p-2 border border-gray-300 rounded-md"
          >
            <option value="">全部状态</option>
            <option value="verifying">验证中</option>
            <option value="pending_submit">待提交</option>
            <option value="pending_distribute">待发放</option>
            <option value="distributing">发放中</option>
            <option value="completed">已完成</option>
            <option value="cancelled">已取消</option>
            <option value="distribute_failed">发放失败</option>
            <option value="verify_failed">验证失败</option>
            <option value="refunded">已退票</option>
          </select>
          <button
            @click="resetFilters"
            class="px-4 py-2 text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200"
          >
            重置
          </button>
        </div>
      </div>

      <!-- 加载状态 -->
      <div v-if="loading" class="text-center py-8">
        <div class="text-gray-500">加载中...</div>
      </div>

      <!-- 结算记录列表 -->
      <div v-else-if="settlements.length > 0" class="space-y-4">
        <div
          v-for="settlement in settlements"
          :key="settlement.id"
          class="bg-white rounded-lg p-4 shadow-sm"
        >
          <!-- 基本信息 -->
          <div class="flex justify-between items-start mb-3">
            <div>
              <h3 class="text-base font-medium text-gray-900">
                结算单号：{{ settlement.sub_settlement_number }}
              </h3>
              <p class="text-sm text-gray-600 mt-1">
                创建时间：{{ settlement.created_at }}
              </p>
            </div>
            <div class="text-right">
              <div
                class="px-2 py-1 rounded-full text-xs font-medium"
                :class="getStatusClass(settlement.status)"
              >
                {{ settlement.status_display }}
              </div>
              <p v-if="settlement.distributed_at" class="text-xs text-gray-500 mt-1">
                发放时间：{{ settlement.distributed_at }}
              </p>
            </div>
          </div>

          <!-- 金额信息 -->
          <div class="space-y-2 text-sm">
            <div class="flex justify-between">
              <span class="text-gray-600">结算前金额:</span>
              <span class="text-gray-900 font-medium">
                ￥{{ parseFloat(settlement.pre_settlement_amount).toLocaleString() }}
              </span>
            </div>
            <div class="flex justify-between">
              <span class="text-gray-600">服务费:</span>
              <span class="text-red-600">
                -￥{{ parseFloat(settlement.service_fee).toLocaleString() }}
                ({{ (settlement.service_fee_rate * 100).toFixed(1) }}%)
              </span>
            </div>
            <div class="flex justify-between border-t pt-2">
              <span class="text-gray-600 font-medium">实际收入:</span>
              <span class="text-green-600 font-bold text-lg">
                ￥{{ parseFloat(settlement.commission).toLocaleString() }}
              </span>
            </div>
          </div>

          <!-- 备注信息 -->
          <div v-if="settlement.payment_remarks || settlement.status_description" class="mt-3 p-3 bg-gray-50 rounded-md">
            <p v-if="settlement.payment_remarks" class="text-sm text-gray-700">
              <span class="font-medium">备注:</span> {{ settlement.payment_remarks }}
            </p>
            <p v-if="settlement.status_description" class="text-sm text-gray-700">
              <span class="font-medium">状态说明:</span> {{ settlement.status_description }}
            </p>
          </div>

          <!-- 电子回单 -->
          <div v-if="settlement.electronic_receipt" class="mt-3 p-3 bg-blue-50 rounded-md">
            <p class="text-sm text-blue-700 font-medium">电子回单信息</p>
            <div class="text-xs text-blue-600 mt-1 space-y-1">
              <p>回单号：{{ settlement.electronic_receipt.receipt_number }}</p>
              <p>银行：{{ settlement.electronic_receipt.bank_name }}</p>
              <p>交易时间：{{ settlement.electronic_receipt.transaction_time }}</p>
            </div>
          </div>

        </div>
      </div>

      <!-- 空状态 -->
      <div v-else class="text-center py-12">
        <div class="text-gray-400 text-4xl mb-4">💰</div>
        <div class="text-gray-500 mb-4">暂无结算记录</div>
        <button
          @click="goToProfile"
          class="px-6 py-2 bg-blue-500 text-white rounded-md hover:bg-blue-600"
        >
          返回首页
        </button>
      </div>

      <!-- 分页 -->
      <div v-if="pagination && pagination.last_page > 1" class="mt-6 flex justify-center">
        <div class="flex space-x-2">
          <button
            @click="loadPage(pagination.current_page - 1)"
            :disabled="pagination.current_page <= 1"
            class="px-3 py-2 border border-gray-300 rounded-md text-sm text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
          >
            上一页
          </button>
          <span class="px-3 py-2 text-sm text-gray-700">
            第 {{ pagination.current_page }} 页，共 {{ pagination.last_page }} 页
          </span>
          <button
            @click="loadPage(pagination.current_page + 1)"
            :disabled="pagination.current_page >= pagination.last_page"
            class="px-3 py-2 border border-gray-300 rounded-md text-sm text-gray-700 bg-white hover:bg-gray-50 disabled:opacity-50"
          >
            下一页
          </button>
        </div>
      </div>
    </div>

  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useApi } from '~/utils/apiConfig'

const loading = ref(true)
const settlements = ref([])
const statistics = ref(null)
const pagination = ref(null)

// 筛选器
const filters = ref({
  status: '',
  page: 1
})

// API 实例
const api = useApi('freelancer')

// Auth composable
const { requireAuth } = useAuth()

/**
 * 获取状态对应的CSS类
 */
const getStatusClass = (status) => {
  const classMap = {
    'verifying': 'bg-yellow-100 text-yellow-800',
    'pending_submit': 'bg-blue-100 text-blue-800',
    'pending_distribute': 'bg-indigo-100 text-indigo-800',
    'distributing': 'bg-purple-100 text-purple-800',
    'completed': 'bg-green-100 text-green-800',
    'cancelled': 'bg-gray-100 text-gray-800',
    'distribute_failed': 'bg-red-100 text-red-800',
    'verify_failed': 'bg-red-100 text-red-800',
    'refunded': 'bg-orange-100 text-orange-800'
  }
  return classMap[status] || 'bg-gray-100 text-gray-800'
}

/**
 * 获取结算记录
 */
const fetchSettlements = async () => {
  loading.value = true
  try {
    const params = new URLSearchParams()
    if (filters.value.status) {
      params.append('status', filters.value.status)
    }
    params.append('page', filters.value.page)
    params.append('per_page', 20)

    const url = `/settlements${params.toString() ? '?' + params.toString() : ''}`
    const response = await api.get(url)

    if (response.code === 0) {
      settlements.value = response.data.settlements || []
      pagination.value = response.data.pagination
    } else {
      throw new Error(response.message || '获取结算记录失败')
    }
  } catch (error) {
    console.error('获取结算记录失败:', error)
    settlements.value = []
    if (error.status === 401 || error.statusCode === 401) {
      await navigateTo('/login?redirect=/settlements')
    }
  } finally {
    loading.value = false
  }
}

/**
 * 获取统计信息
 */
const fetchStatistics = async () => {
  try {
    const response = await api.get('/settlements-statistics')
    if (response.code === 0) {
      statistics.value = response.data
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

/**
 * 重置筛选器
 */
const resetFilters = () => {
  filters.value = {
    status: '',
    page: 1
  }
  fetchSettlements()
}

/**
 * 切换页面
 */
const loadPage = (page) => {
  if (page < 1 || (pagination.value && page > pagination.value.last_page)) {
    return
  }
  filters.value.page = page
  fetchSettlements()
}

/**
 * 返回首页
 */
const goToProfile = () => {
  navigateTo('/profile')
}

// 页面初始化
onMounted(async () => {
  await requireAuth()
  await Promise.all([
    fetchSettlements(),
    fetchStatistics()
  ])
})
</script>
